/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gebze.Util;

import java.io.*;

/**
 * Server tarafından her client için dinleme clası
 *
 * @author Özcan ÇAĞIRICI <ozcan.cagirici@gmail.com>
 *
 * @author Hatice Şahin <haticesahin.09@gmail.com>
 */
public class GbzScannerClientHandler extends Thread {

    private BufferedReader in;
    private InputStream ins;
    private OutputStreamWriter out;
    private OutputStream outs;
    private transient boolean connected = true;
    private boolean isConnected;

    public GbzScannerClientHandler(InputStream ins, OutputStream outs) {
        this.ins = ins;
        this.outs = outs;
        Reader isread = new InputStreamReader(ins);
        in = new BufferedReader(isread);
        out = new OutputStreamWriter(outs);
        isConnected = true;
    }

    @Override
    public void run() {
        sendMessage("hello client");
        while (isConnected) {
            //bir değişken yardımıyla, mmesaj gönderilip
            //gönderilmeyeceği kontrol edilecek. ve client ile mesajlaşacak.
            System.out.println(getClientMessage());
            sendMessage("tamam");
        }
    }

    /**
     * client tarafından gelen mesajların okundugu method
     *
     * @return
     */
    public String getClientMessage() {
        String clientMesaji = null;
        try {
            clientMesaji = in.readLine();
        } catch (IOException ex) {
            System.out.println("Mesaj okunurken hata olustu: " + ex);
        }

        return clientMesaji;
    }

    /**
     * serverin istegini(mesajını) clienta gonderir.
     *
     * @param serverMesaj
     */
    public void sendMessage(String serverMesaj) {

        try {
            out.write(serverMesaj + "\n");
            out.flush();
        } catch (IOException ex) {
            System.out.println("Mesaj gonderilemedi.. ");
        }
    }

    public BufferedReader getIn() {
        return in;
    }

    public void setIn(BufferedReader in) {
        this.in = in;
    }

    public OutputStreamWriter getOut() {
        return out;
    }

    public void setOut(OutputStreamWriter out) {
        this.out = out;
    }

    public InputStream getIns() {
        return ins;
    }

    public void setIns(InputStream ins) {
        this.ins = ins;
    }

    public OutputStream getOuts() {
        return outs;
    }

    public void setOuts(OutputStream outs) {
        this.outs = outs;
    }

    public boolean isConnected() {
        return connected;
    }

    public void setConnected(boolean connected) {
        this.connected = connected;
    }
}